<template>
  <div>
    <div class="w-form-header">
      <!-- <span> 创建大办单 </span> -->
      <div>
        <el-button v-if="submitBtn" type="primary" @click="save()" :disabled=submitBtn2
          >保存</el-button
        >
        <el-button v-else type="primary" @click="save()">创建</el-button>
      </div>
    </div>
    <div class="gva-form-box admin-content">
      <div class="w-form-box">
        <div class="list-header">基础信息</div>
        <el-form
          :model="formData"
          ref="elFormRef"
          label-position="right"
          :rules="rule"
          label-width="90px"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item
                :label="`${il8n('styleNum.label')}:`"
                prop="styleNum"
              >
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                  "
                >
                  <el-select
                    v-model="formData.styleNum"
                    clearable
                    filterable
                    style="min-width: 150px; margin-right: 10px"
                    :disabled="true"
                    @click="openCreateAndEdit"
                    placeholder="点击查询"
                    remote
                    :remote-method="
                        getProductStylesListFn
                    "
                    @change="getSizesAndDDMS"
                  >
                    <el-option
                      v-for="item in productStylesList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <el-icon @click="openCreateAndEdit"><Search /></el-icon>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="`${il8n('customerDemandDate.label')}:`"
                prop="customerDemandDate"
                label-width="120px"
              >
                <el-date-picker
                  :disabled-date="disabledDate"
                  style="width: 100%"
                  v-model="formData.customerDemandDate"
                  type="date"
                  value-format="YYYY-MM-DDTHH:mm:ssZ"
                  :placeholder="il8n('customerDemandDate.placeholder')"
                  :clearable="true"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`PI客户要求完成日期:`" prop="piDemandDate" label-width="160px">
                <el-date-picker
                  :disabled-date="disabledDate"
                  v-model="formData.piDemandDate"
                  type="date"
                  value-format="YYYY-MM-DDTHH:mm:ssZ"
                  placeholder="选择日期"
                  :clearable="true"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="`办单付数:`" prop="plmOrderNum">
                <LTable
                  v-if="tableData.length <= 0"
                  :columns="columns"
                  :tableData="[]"
                  :pagination="false"
                  :selection="false"
                  :showConfig="false"
                  style="width: 100%"
                  ref="tableRef"
                ></LTable>
                <LTable
                  v-else
                  :columns="columns"
                  :tableData="tableData"
                  :pagination="false"
                  :selection="false"
                  :tableProps="{
                    showSummary: true,
                    summaryMethod: getSumaryMethod,
                  }"
                  :showConfig="false"
                  style="width: 100%"
                  ref="tableRef"
                >
                  <template #color="{ row, column }">
                    <el-input
                      v-model="row.colorNum[column.prop]"
                      @input="validNumber(row.colorNum, column.prop)"
                    />
                  </template>
                  <template #luckTilt="{ row }">
                    <span
                      ><el-input-number
                        :controls="false"
                        style="width: 60px; height: 28px"
                        :max="255"
                        :min="0"
                        v-model="row.luckTilt"
                    /></span>
                  </template>
                  <template #count="{ row }">
                    <span>{{ getCount(row) }}</span>
                  </template>
                  <template #design="{ row }">
                    <el-select v-model="row.drawingList" :clearable="true">
                      <el-option
                        v-for="item in row.ddmsDrawingLists"
                        :key="item.ID"
                        :label="item.drawingName"
                        :value="item.fileUrl"
                      >
                      <span>{{ item.drawingName }}{{ (item.status==0 ? '(草稿)' : item.status==1?'(完成)' : item.status==2 ? '(审批中)' : '') }}</span>
                    </el-option>
                    </el-select>
                  </template>
                </LTable>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="办单去向：">
                <!-- <span v-for="(item, index) in dict?.firstOrderDest" :key="index"
                  >{{ item.label }}
                  <el-input-number
                    :min="0"
                    :controls="false"
                    v-model="formData.orderTo[item.label]"
                    style="margin: 0 8px;width: 100px;"
                /></span> -->
                <template v-if="formData.cumstomerNum != 'ST101'">
                  <span
                    v-for="(item, index) in dict?.firstOrderDestNoST101"
                    style="margin-right: 12px"
                    >{{ item.label
                    }}<el-input-number
                      :min="0"
                      v-if="formData.orderTo"
                      :disabled="item.label == '其他' || !orderToNums"
                      :controls="false"
                      v-model="formData.orderTo[item.label]"
                      style="margin-left: 8px; width: 33px"
                      @change="changeOhterNums"
                  />&ensp;付</span>
                </template>
                <template v-else>
                  <span
                    v-for="(item, index) in dict?.firstOrderDestST101"
                    style="margin-right: 12px"
                    >{{ item.label
                    }}<el-input-number
                      :min="0"
                      v-if="formData.orderTo"
                      :disabled="item.label == '其他' || !orderToNums"
                      :controls="false"
                      @change="changeOhterNums"
                      v-model="formData.orderTo[item.label]"
                      style="margin-left: 8px; width: 33px"
                  />&ensp;付</span>
                </template>

              </el-form-item>
            </el-col>
            <el-col
              :span="24"
              v-if="formData.orderTo && formData.orderTo['其他'] && formData.orderTo['其他'] > 0"
            >
              <el-form-item :label="`其他原因:`" prop="orderTo.otherReason">
                <el-input
                  v-model="formData.orderTo['otherReason']"
                  type="textarea"
                  :autosize="{ minRows: 1}"
                  :maxlength="500"
                  show-word-limit
                  placeholder=""
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="办单类型：">
                <el-select
                  v-model="formData.orderProcessType"
                  :clearable="true"
                >
                  <el-option
                    v-for="item in dict?.orderType"
                    :key="item.ID"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="附办数量：">
                <el-input-number
                  style="width: 100%"
                  class="orderAmount"
                  v-model="formData.orderAmount"
                  placeholder="请输入附办数量"
                  :controls="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`印资：`">
                <el-radio-group v-model="formData.requireLetterpressMaterial">
                  <el-radio label="需要">需要</el-radio>
                  <el-radio label="不需要">不需要</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`是否新款：`">
                <el-radio-group v-model="formData.isNewStyle">
                  <el-radio label="是">是</el-radio>
                  <el-radio label="否">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`吉架要求完成：`" prop="jijiaDemandDate" label-width="100px">
                <el-date-picker
                  :disabled-date="disabledDate"
                  style="width: 100%"
                  v-model="formData.jijiaDemandDate"
                  type="date"
                  value-format="YYYY-MM-DDTHH:mm:ssZ"
                  placeholder="选择日期"
                  :clearable="true"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`首办单回单：`">
                <el-radio-group v-model="formData.firstOrderReceipt">
                  <el-radio label="有">有</el-radio>
                  <el-radio label="无">无 </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="參考首办单：">
                <!-- <el-input-number v-model="formData.referFirstOrderProcess" placeholder="系统自动填写" :controls="false" /> -->
                <el-select
                  placeholder="选择参考首办单"
                  clearable
                  filterable
                  v-model="formData.referFirstOrderProcess"
                >
                  <el-option
                    v-for="item in firstOrderProcessingList"
                    :key="item.ID"
                    :label="item.firstOrderNum"
                    :value="item.firstOrderNum"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="PI编号：">
                <el-input
                  v-model="formData.piOrderNum"
                  placeholder="自定义填写"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="首办单回单备注：" label-width="120px">
                <el-select
                  v-model="formData.firstOrderReceiptNote"
                  :clearable="true"
                >
                  <el-option
                    v-for="item in dict?.firstOrderReceiptNote"
                    :key="item.ID"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="生产地点：" prop="transferOrder">
                <el-select v-model="formData.transferOrder" :clearable="true">
                  <el-option
                    v-for="(item, index) in transferOrder"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`参与周期计算：`" label-width="120px">
                <el-radio-group v-model="formData.isCycleCountIn">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否 </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`For specasavers：`" label-width="120px">
                <el-radio-group v-model="formData.isForSpecasavers">
                  <el-radio label="是">是</el-radio>
                  <el-radio label="否">否 </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="`款式备注：`" prop="productStyleNote">
                <el-input
                  v-model="formData.productStyleNote"
                  type="textarea"
                  :disabled="true"
                  :autosize="{ minRows: 1 }"
                  :maxlength="500"
                  show-word-limit
                  placeholder="自动获取"
                  :clearable="true"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item :label="`大办单备注：`" prop="largeScaleNote">
                <el-input
                  v-model="formData.largeScaleNote"
                  type="textarea"
                  :autosize="{ minRows: 1 }"
                  :maxlength="500"
                  show-word-limit
                  placeholder=""
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`刻字模备注：`" prop="engraveMoldNote">
                <el-input
                  v-model="formData.engraveMoldNote"
                  type="textarea"
                  :autosize="{ minRows: 1 }"
                  :maxlength="500"
                  show-word-limit
                  placeholder=""
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`附办说明：`" prop="orderExplain">
                <el-input
                  v-model="formData.orderExplain"
                  type="textarea"
                  :autosize="{ minRows: 1 }"
                  :maxlength="500"
                  show-word-limit
                  placeholder=""
                  :clearable="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="formData.version >= 1">
                <el-form-item :label="`修改备注：`" prop="modifyNote">
                    <el-input
                        v-model="formData.modifyNote"
                        type="textarea"
                        :autosize="{ minRows: 1 }"
                        :maxlength="500"
                        show-word-limit
                        placeholder=""
                        :clearable="true"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="24" v-if=" formData.version>1">
            <div >
                <div class="w-form-box">
                    <div class="list-header">与上版本配件对比</div>
                </div>
                <!-- <div class="version-PK">
                    <el-descriptions title="" :column="1" border>
                        <el-descriptions-item label="新增配件" label-align="center">{{addAccessory.join(',')}}</el-descriptions-item>
                        <el-descriptions-item label="删除配件"  label-class-name="delete-acc" label-align="center">{{deleteAccessory.join(',')}}</el-descriptions-item>
                    </el-descriptions>
                </div> -->
                <div>
                  <el-table
                      :data="[{
                        addAccessory:addAccessory.join(','),
                        deleteAccessory:deleteAccessory.join(',')
                      }]"
                      border
                      class=".table-style-1"
                      style="width: 100%"
                  >
                      <el-table-column
                          label="新增配件"
                          prop="addAccessory"
                          min-width="300"
                      >
                        <template #default="{ row }">
                          <div v-for="item in addAccessory">{{item}}</div>
                        </template>
                      </el-table-column>
                      <el-table-column
                          label="删除配件"
                          prop="deleteAccessory"
                          min-width="300"
                      >
                        <template #default="{ row }">
                          <div v-for="item in deleteAccessory">{{item}}</div>
                        </template>
                      </el-table-column>
                  </el-table>
                </div>
            </div>
          </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- <el-row type="flex" justify="center" style="margin-top: 20px">
                <el-button type="primary" @click="save">保存草稿</el-button>
                <el-button type="primary" @click="back">返回</el-button>
            </el-row> -->
      <styleNumSearch
        v-if="editReasonDialogShow"
        @closeDialog="closeDialog"
        @selectStyleNum="selectStyleNum"
        searchType="plmLargeOrderProcessing"
      ></styleNumSearch>
    </div>
  </div>
</template>

<script setup>
// import { createFirstOrderProcessing } from "@/api/plmFirstOrderProcessing";
import {
  createLargeScaleOrder,
  firstOrderProcessingListByStyleNum,
  updateLargeScaleOrder,
  findLargeScaleOrder,
  versionComparison,
} from "@/api/plmLargeScaleOrder";
import { getProductSpecSizeList } from "@/api/productSpecSize";
import { getProductStylesList } from "@/api/plmProductStyles";
import { getDdmsSpecDrawingListList } from "@/api/ddmsSpecDrawingList";
import { getProductSpecColorList } from "@/api/productSpecColor";
defineOptions({
  name: "FirstOrderProcessingForm",
});
import { disabledDate } from "../../utils/tool";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, toRefs, reactive, onMounted, unref } from "vue";
import { useI18n } from "vue-i18n";
import LTable from "@/components/LTable/LTable.vue";
import { useDict } from "@/utils/dictionary";
import { emitter } from "@/utils/bus.js";
import styleNumSearch from "@/components/styleNumSearch/styleNumSearch.vue";
import { findProductSpec } from "@/api/plmProductSpec";
import { findProductStyles } from "@/api/plmProductStyles";
const dict = ref({});

const { t: il8n } = useI18n();
console.log("add============", il8n("styleNum.label"));
const router = useRouter();
const route = useRoute();

const elFormRef = ref();
const productStylesList = ref([]);
const ddmsDrawingList = ref([]);
const firstOrderProcessingList = ref([]);
const sizes = ref({});
const colorList = ref([]);
const submitBtn = ref(false);
const submitBtn2 = ref(false);

const orderToNums = ref(0)
const initColumns = [
  {
    prop: "sizeNum",
    fixedWidth: 100,
    label: "尺码",
    show: true,
    tableColumnProps: {
      fixed: "left",
      sortable: false,
    },
  },
  {
    prop: "luckTilt",
    fixedWidth: 100,
    label: "吉架",
    show: true,
    tableColumnProps: {
      fixed: "right",
      sortable: false,
    },
    slot: "luckTilt",
  },
  {
    prop: "amountTotal",
    fixedWidth: 100,
    label: "总计",
    show: true,
    tableColumnProps: {
      fixed: "right",
      sortable: false,
    },
    slot: "count",
  },
  {
    prop: "design",
    width: 200,
    label: "设计规格图",
    show: true,
    tableColumnProps: {
      fixed: "right",
      sortable: false,
    },
    slot: "design",
  },
];
const columns = ref(initColumns);
const tableData = ref([]);

const formData = ref({orderTo: {"其他": 0}})
// 验证规则
const rule = ref({
  "orderTo.otherReason": [
    { required: true, message: "请输入其他原因", trigger: "blur" },
    ],
    customerDemandDate: [{ required: true, message: "请选择客户要求完成时间", trigger: "blur" }],
    plmOrderNum: [{
        validator: (rule, value, callback) => {
            const tdata = tableData.value
            let count = 0
            tdata.forEach(f => {
              const nums = getCount(f)
                if (nums > 0 && !f.drawingList) {
                callback(new Error('尺码合计付数大于0，请选择设计规格图'))  
                return
                }
                count += nums
            })
    
            if (count <= 0) {
                callback(new Error('尺码合计付数不能为0'))
                return
            }
            callback()
        }
    }],
    // transferOrder: [{ required: true, message: "请选择生产地点", trigger: "blur" }],
    modifyNote: [{ required: true, message: "请输入修改备注", trigger: "blur" }]
});


const transferOrder = ref([]);

onMounted(async () => {
  dict.value = await useDict(
    "firstOrderDestST101",
    "firstOrderDestNoST101",
    "orderType",
    "firstOrderReceiptNote"
  );

  // 获取产品款式列表
  // getProductStylesListFn();

  const {
    query: { id },
  } = route;
  if (id) {
    submitBtn.value = true;
    getFindLargeOrderProcessingDetail(id);
  }
});

// 保存按钮
const save = async (status) => {
  elFormRef.value?.validate(async (valid) => {
    if (valid && compareNums(tableData.value, formData.value.orderTo)) {
      tableData.value.forEach(vv=>{
        let ll = vv.ddmsDrawingLists?.filter(val=> val.fileUrl == vv.drawingList)
        if(ll && ll.length>0){
          vv['drawingName'] = ll[0].drawingName
          vv["ddmsNum"] = ll[0].ddmsNum || '';
          vv["ddmsNumVersion"] = ll[0].version || '';
        }else{
          vv["drawingName"] = '';
          vv["ddmsNum"] = '';
          vv["ddmsNumVersion"] = '';
        }
      })
      if (formData.value.ID) {
        console.log('提交11');
        
        confirmNoReasonForm();
      } else {
      
        const tableD = unref(tableData);
        let orderAmountSum = 0;
        tableD.forEach((item) => {
          item.amountTotal = getCount(item) || 0;
          orderAmountSum += Number(item.amountTotal);
        });
        // console.log("tableData====================", formData.value);
        // return
        const params = {
          ...formData.value,
          orderAmountSum,
          sizes: tableD,
          status: status || undefined,
          orderAmount: String(formData.value.orderAmount),
        };

        const res = await createLargeScaleOrder(params);
        if (res.code === 0) {
          ElMessage({
            type: "success",
            message: "创建成功",
          });
          // back();
          // getFindLargeOrderProcessingDetail(res.data)
          emitter.emit("closeThisPage", {
            path: "/layout/plmLargeOrderProcessingEdit",
            query: { id: res.data, subTitle: res.data },
          });
        }
      }
    }
  });
};

// 返回按钮
const back = () => {
  router.push({
    path: "/layout/plmLargeOrderProcessing",
  });
};

async function getProductStylesListFn(keyword) {
  const res = await getProductStylesList({
    page: 1,
    pageSize: 200,
    productSpecStatus: "1",
    status: "1",
    styleNum:keyword
  });
  if (res.code === 0) {
    productStylesList.value = res.data.list.map((rdlm) => ({
      value: rdlm.styleNum,
      label: rdlm.styleNum,
      transferOrderRange: rdlm.transferOrderRange,
      cumstomerNum:rdlm.cumstomerNum
    }));

  }
}

function getCount(row) {
  let num = 0;
  for (const key in row.colorNum) {
    num += Number(row.colorNum[key] || 0);
  }
  num += Number(row.luckTilt) || 0;
  return num || null;
}

function getSizesAndDDMS(params) {
  if (!formData.value.styleNum) {
    colorList.value = [];
    tableData.value = [];
    ddmsDrawingList.value = [];
    return;
  }
  // const pdsl = unref(productStylesList);
  // const item = pdsl.find((f) => f.value === formData.value.styleNum);
  // 获取转单范围
  getTransferOrderRange(params);
  getColor(formData.value.styleNum);
  getFirstOrderProcessingListByStyleNum(formData.value.styleNum);
  // 获取规格参数
  getGuige(formData.value.styleNum);
}

function getGuige(params) {
  findProductSpec({ styleNum: params }).then((res) => {
    if (res.code == 0) {
      formData.value.productStyleNote = res.data.reproductSpec.styleNote;
    }
  });
}

function getTransferOrderRange(params) {
  // const pdsl = unref(productStylesList);
  // const item = pdsl.find((f) => f.value === styleNum);
  formData.value.cumstomerNum = params?.cumstomerNum || ''
  if(formData.value.cumstomerNum=='ST101') {
    dict.value.firstOrderDestST101.forEach(item=>{
      formData.value.orderTo[item.value] = 0 
    })
  }else {
    dict.value.firstOrderDestNoST101.forEach(item=>{
      formData.value.orderTo[item.value] = 0 
    })
  }
  transferOrder.value = params?.transferOrderRange || [];
}

// 获取颜色
function getColor(styleNum) {
  getProductSpecColorList({ page: 1, pageSize: 999, styleNum }).then((res) => {
    if (res.code == 0) {
      colorList.value = res.data.list;
      const col = res.data.list.map((item) => {
        return {
          prop: item.colorNum,
          label: item.colorNum,
          show: true,
          fixedWidth: 80,
          tableColumnProps: {
            sortable: false,
          },
          slot: "color",
        };
      });
      const newColumns = [...initColumns];
      if (col.length > 0) {
        newColumns.splice(1, 0, ...col);
      }
      columns.value = newColumns;
      getSizes(styleNum);
    }
  });
}

function getSizes(styleNum) {
  getProductSpecSizeList({ styleNum }).then((res) => {
    if (res.code === 0) {
      const { data } = res;
      sizes.value = data.list;
      tableData.value = data.list;
      tableData.value.forEach((item) => {
        item.colorNum = {};
        colorList.value.forEach((it) => {
          item.colorNum[it.colorNum] = null;
        });
      });
      console.log("tableData====================", tableData.value);
      tableData.value.map((m, index) => {
        getDDMS(index, formData.value.styleNum, m.sizeNum);
      });
    }
  });
}

function getDDMS(dataIndex, styleNum, sizeNum) {
  getDdmsSpecDrawingListList({ styleNum, sizeNum }).then((res) => {
    if (res.code === 0) {
      const { data } = res;
      tableData.value[dataIndex].ddmsDrawingLists = data.list;
    }
  });
}

function getFirstOrderProcessingListByStyleNum(styleNum) {
  firstOrderProcessingListByStyleNum({ styleNum }).then((res) => {
    if (res.code === 0) {
      const { data } = res;
      firstOrderProcessingList.value = data.list;
    }
  });
}

// 判断办单付数 和 办单去向总数数量对比
function compareNums(sizes = [], firstOrderDest = {}) {
  let firstOrderDestNums = 0;
  for (let key in firstOrderDest) {
    if (firstOrderDest[key] && key !== "otherReason") {
      firstOrderDestNums += Number(firstOrderDest[key]);
    }
  }
  let sizeNums = 0;
  sizes.map((sm) => {
    if (sm.colorNum) {
      for (let key in sm.colorNum) {
        if (sm.colorNum[key]) {
          sizeNums += Number(sm.colorNum[key]);
        }
      }
    }
    if (sm.luckTilt) sizeNums += Number(sm.luckTilt);
  });
  if (firstOrderDestNums !== sizeNums) {
    ElMessage({
      type: "error",
      message: "办单去向总数只能等于办单付数总数",
    });
    return false;
  }
  return true;
}

// 对比2个数组
function compareArray(arr1 = [], arr2 = []) {
  const arr1Map = new Map();
  const newArr = [];
  arr1.map((m) => arr1Map.set(m.sizeNum, m));
  arr2.map((m) => {
    if (arr1Map.has(m.sizeNum)) {
      newArr.push(arr1Map.get(m.sizeNum));
    } else {
      newArr.push(m);
    }
  });
  return newArr;
}

function validNumber(data, type) {
  data[type] = data[type].replace(/[^0-9]/gi, "");
}

async function confirmNoReasonForm() {
  const relargeScaleOrder = {
    ...formData.value,
  };
  let orderAmountSum = 0;
  relargeScaleOrder.sizes = tableData.value;
  relargeScaleOrder.sizes.forEach((item) => {
    item.amountTotal = getCount(item);
    orderAmountSum += Number(item.amountTotal);
    let ll = item.ddmsDrawingLists?.filter(
        (val) => val.fileUrl == item.drawingList
    );
    if (ll && ll.length > 0) {
        item["drawingName"] = ll[0].drawingName;
        item["ddmsNum"] = ll[0].ddmsNum || '';
        item["ddmsNumVersion"] = ll[0].version || '';
    }else{
      item["drawingName"] = '';
      item["ddmsNum"] = '';
      item["ddmsNumVersion"] = '';
    }
  });
  // relargeScaleOrder.colors = colorTableData.value;
  // relargeScaleOrder.accessorySpecs = sourceAccessorySpecs.value;
  // relargeScaleOrder.signs = signTableData.value;
  // relargeScaleOrder.modifyNotes = historyNoteTableData.value;
  // relargeScaleOrder.tests = testStandardDocumentListData.value;
  relargeScaleOrder.orderAmount = String(relargeScaleOrder.orderAmount);
  relargeScaleOrder.orderAmountSum = orderAmountSum;
  
  const params = { ...relargeScaleOrder };
  console.log("params=============", params);
  submitBtn2.value = true
  const res = await updateLargeScaleOrder(params);
 console.log(res,'111');
 if(res.msg){
  submitBtn2.value = false
 }
 
  if (res.code === 0) {
    submitBtn2.value = false
    // addNoteForm.value = {};
    ElMessage({
      type: "success",
      message: "修改成功",
    });
    const {
      query: { id },
    } = route;
    emitter.emit("closeThisPage", {
      path: "/layout/plmLargeOrderProcessingEdit",
      query: { id: id, subTitle: id },
    });
  }
}

async function getFindLargeOrderProcessingDetail(largeScaleNum) {
  const res = await findLargeScaleOrder({ largeScaleNum });
  if (res.code === 0) {
    const {
      data: {
        relargeScaleOrder,
        relargeScaleOrder: {
          sizes = [],
          colors = [],
          accessorySpecs = [],
          signs = [],
          modifyNotes = [],
          mold_house = [],
          tests = [],
        },
      },
    } = res;
    formData.value = relargeScaleOrder;
    // transferOrder.value = relargeScaleOrder.transferOrderRange || [];
    findProductStyles({
        styleNum: formData.value.styleNum,
    }).then((res) => {
        transferOrder.value = res.data.reproductStyles.transferOrderRange || []
        // 日期比 2024-07-22前不校验时间
        // const date1 = new Date('2024-07-22');
        // const date2 = new Date(res.data.reproductStyles.CreatedAt);
        // console.log("--->",res.data.reproductStyles.CreatedAt)
        // if(date1.getTime() > date2.getTime()){
        //   if(rule.value.transferOrder) delete rule.value.transferOrder
        // }
    });
    const colorRes = await findProductSpec({
        styleNum: formData.value.styleNum,
    });
    let productColors = colorRes.data.reproductSpec.colors
    const sizsRes = await getProductSpecSizeList({
      styleNum: formData.value.styleNum,
    });
    sizes.map(sizesItem=>{
      if(sizesItem.colorNum){
        Object.keys(sizesItem.colorNum).forEach(key=>{
          if(!productColors.some(s=> s.colorNum == key)){
            delete sizesItem.colorNum[key]
          }
        })
      }
    })
    const sizeL = compareArray(sizes, sizsRes?.data?.list);
    
    const col = productColors.map((item) => {
      return {
        prop: item.colorNum,
        label: item.colorNum,
        show: true,
        fixedWidth: 80,
        tableColumnProps: {
          sortable: false,
        },
        slot: "color",
      };
    });
    const newColumns = [...initColumns];
    if (col.length > 0) {
      newColumns.splice(1, 0, ...col);
    }
    columns.value = newColumns;
    // 去除旧图
    let index = columns.value.findIndex(item=>{
        return item.prop == 'design'
    })
    let oldName = ''
    if(index!=-1){
        oldName = sizeL.map(sizeItem=>{
            return sizeItem.drawingName || ''
        }).join(';')
        columns.value[index].label = "设计规格图" + `(上次用图:${oldName})`
    }
    tableData.value = sizeL.map((m) => {
      if (!m.colorNum) m.colorNum = {};
      m['drawingList'] = ''
      m['drawingName'] = ''
      return m;
    });
    // colorTableData.value = colors;
    // sourceAccessorySpecs.value = deepClone2(accessorySpecs);
    // partTableData.value = initAccessorySpecs(accessorySpecs);
    // testStandardDocumentListData.value = tests;
    // signTableData.value = signs;
    // historyNoteTableData.value = modifyNotes;
    // boardMakingTalbeData.value = mold_house;
    // 获取设计图列表
    // ddmsSpecDrawingListList(relargeScaleOrder.styleNum);

    console.log(22223333,relargeScaleOrder);
    if(relargeScaleOrder.version>1) {
            getAccessoryData()
        }
    tableData.value.map((m, index) => {
      getDDMS(index, formData.value.styleNum, m.sizeNum);
    });
  }
}

function getSumaryMethod(SummaryMethodProps) {
  console.log(3333,SummaryMethodProps);
  const { columns, data = [] } = SummaryMethodProps;
  const sums = [];
  let otherNums = 0
  columns.forEach((column, index) => {
    if (column.property === "luckTilt") {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => getCount(item));
    if (
      column.property === "amountTotal" &&
      !values.every((value) => Number.isNaN(value))
    ) {
        sums[index] = values.reduce((a, b) => a + b, 0);
        otherNums = sums[index]
    }
  });
  orderToNums.value = otherNums
  if(!formData.value.orderTo){
    formData.value.orderTo = {
      '其他': 0
    } 
  }
  else formData.value.orderTo['其他'] = otherNums
  changeOhterNums()
  return sums;
}

// 款式查询弹窗
const editReasonDialogShow = ref(false);
// 打开 新增、编辑
const openCreateAndEdit = () => {
  editReasonDialogShow.value = true;
};

// 关闭款式查询弹窗
function closeDialog(params) {
  editReasonDialogShow.value = false;
}

function selectStyleNum(params) {
  formData.value.styleNum = params.styleNum;
  getSizesAndDDMS(params);
  editReasonDialogShow.value = false;
}

function changeOhterNums() {
        let otherNums = 0
        for (let key in formData.value.orderTo) {
            if (key !== '其他'&&key!=='otherReason') {
                otherNums += formData.value.orderTo[key]
            }
        }
        formData.value.orderTo['其他'] =orderToNums.value - otherNums || 0
}

// 新增与上版本配件对比
const addAccessory = ref([]);
const deleteAccessory = ref([]);
function getAccessoryData(params) {
    const {
        query: { id },
    } = route;
    versionComparison({largeScaleNum: id}).then(res=>{
        if(res.code==0) {
            addAccessory.value = []
            deleteAccessory.value = []
            if (res.data.Add) {
                res.data.Add.map((item) => {
                    let idx = addAccessory.value.findIndex((p) => {
                        return p == (item.componentNum || '') + (item.colorNum || '')
                    });
                    let p = (item.componentNum || '') + (item.colorNum || '')
                    if (idx == -1 && p) {
                        addAccessory.value.push(p);
                    }
                });
            }
            if (res.data.Decrease) {
                res.data.Decrease.map((item) => {
                    let idx = deleteAccessory.value.findIndex((p) => {
                        return p == (item.componentNum || '') + (item.colorNum || '')
                    });
                    let p = (item.componentNum || '') + (item.colorNum || '')
                    if (idx == -1 && p) {
                        deleteAccessory.value.push(p);
                    }
                });
            }
        }
    })
}
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
.color-box {
  display: flex;
  align-items: center;
}
.orderAmount {
  :deep(.el-input__inner) {
    text-align: left;
  }
}

.version-PK {
    :deep(.delete-acc) {
    background: #fd9595 !important;
    color: #000 !important;
}
:deep(.table-style-1){
    .el-table__cell{
        vertical-align: top !important;
    }    
}
:deep(.el-descriptions__label) {
    width: 10%;
}
}
</style>
